import Crc from '../ble_sdk/crc'
import {
	BleManager
} from '../ble_sdk/v3'
import {
	formatNum,
	dec2hex,
	hex2dec,
	hex2ascll,
	parseShort
} from '../util'
// import { wavelet_filter_convert } from '../ble_sdk/waveFiltering'
// import * as echarts from '../../ec-canvas/echarts'

const fs = wx.getFileSystemManager()
// CRC16 计算函数
function crc16(data) {
	let crc = 0xFFFF;

	for (let i = 0; i < data.length; i++) {
		crc ^= data[i];

		for (let j = 0; j < 8; j++) {
			if ((crc & 0x0001) !== 0) {
				crc >>= 1;
				crc ^= 0xA001; // 多项式：0x8005 按位反转
			} else {
				crc >>= 1;
			}
		}
	}
	return crc;
}

// 创建数据包函数
function createPacket(commandId, parameters = []) {
	const startByte = 0x5A;
	const paramLength = parameters.length;
	const packetLength = 1 + 1 + 1 + paramLength + 2;
	const packet = [];

	// 添加起始字节
	packet.push(startByte);
	// 添加包字节数
	packet.push(packetLength);
	// 添加命令 ID
	packet.push(commandId);
	// 添加数据参数
	packet.push(...parameters);

	// 计算 CRC16
	const crc = crc16(packet);
	const crcHigh = (crc >> 8) & 0xFF;
	const crcLow = crc & 0xFF;
	packet.push(crcHigh, crcLow);

	return packet;
}
// 解析实时袖带压和心跳状态数据包的函数
function parsePacket(hexData) {
	const buffer = Buffer.from(hexData, 'hex');
	console.log("buffer",buffer,buffer[3])
	const startByte = buffer[0];
	const packetLength = buffer[1];
	const commandId = buffer[2];
	const cuffPressureData = (buffer[3] << 8) | buffer[4];
	const heartRateStatus = buffer[5];
	const receivedCrc = (buffer[6] << 8) | buffer[7];
	const dataForCrc = buffer.slice(0, 6);
	const calculatedCrc = crc16(dataForCrc);
	const battery=buffer[3]
	// if (receivedCrc === calculatedCrc) {
	// 	console.log('CRC16 校验通过');
	// } else {
	// 	console.log('CRC16 校验失败');
	// }

	return {
		startByte: startByte.toString(16),
		packetLength,
		commandId: commandId.toString(16),
		cuffPressureData,
		heartRateStatus,
		receivedCrc: receivedCrc.toString(16),
		calculatedCrc: calculatedCrc.toString(16),
		battery
	};
}

// 解析测量结束数据
function parseNewFormatPacket(hexData) {
	const buffer = Buffer.from(hexData, 'hex');
	const startByte = buffer[0];
	const packetLength = buffer[1];
	const commandId = buffer[2];
	const systolicPressure = (buffer[3] << 8) | buffer[4];
	const diastolicPressure = buffer[5];
	const heartRate = buffer[6];
	const year = buffer[7];
	const month = buffer[8];
	const day = buffer[9];
	const hour = buffer[10];
	const minute = buffer[11];
	const errorCode = buffer[12];
	const reserved = buffer[13];
	const receivedCrc = (buffer[14] << 8) | buffer[15];
	const dataForCrc = buffer.slice(0, 14);
	const calculatedCrc = crc16(dataForCrc);
	
	// if (receivedCrc === calculatedCrc) {
	// 	console.log('CRC16 校验通过');
	// } else {
	// 	console.log('CRC16 校验失败');
	// }

	return {
		startByte: startByte.toString(16),
		packetLength,
		commandId: commandId.toString(16),
		systolicPressure,
		diastolicPressure,
		heartRate,
		year: 2000 + year,
		month,
		day,
		hour,
		minute,
		errorCode,
		reserved,
		receivedCrc: receivedCrc.toString(16),
		calculatedCrc: calculatedCrc.toString(16)
	};
}

module.exports = class BP2Protocol extends BleManager {
	streamNo = 0 // 指令流水号
	cmdRecord = '' // 记录上位机给设备端发送的指令，用来和接收的数据包做对应
	reversedCmdRecord = '' // 同上
	datas = '' // 收到的设备端数据包全量
	oldCallbackData = '' // 上一次的数据包，用来判断是否是重复包
	deviceInfo = null // 存设备信息
	heartBeatSoundOn = false // 当前设备的心跳音状态
	devicePercent = 0 // 电量
	deviceRunInfo = {
		runStatus: -1
	} // 当前设备的运行状态
	deviceRunStatus = 0 //设备运行状态
	battery=0//电量

	constructor(Device) {
		super(Device)
	}

	// 生成指令，入参都是16进制string
	generateCmd(cmd, data) {
		const commandId = cmd;
		const parameters = data; // 握手指令无参数
		if(commandId=='0x40'){
			console.log("每次,都走到这里了吗",this.battery)
			this.battery=0;
			console.log("我重置了",this.battery)
		}
		const packet = createPacket(commandId, parameters);
		// 将 packet 数组转换为不带 0x 头的十六进制字符串指令
		const str = packet.map(byte => byte.toString(16).padStart(2, '0')).join('');
		console.log("生成的十六进制指令: ", str);
		return str
	}

	// 解析接受到的设备端数据包
	parseData(res) {
		//不要存储不是以5a开头脏的数据
		if (this.datas == '' && !res.startsWith('5a')) {
			return;
		}

		// // 要解析的十六进制数据
		// const hexData = '5a083d0059011c1b';
		// const parsedData = parsePacket(hexData);
		// console.log('解析结果:', parsedData);

		// // 要解析的新格式十六进制数据
		// const newHexData = '5a100c006c494e1904181712000083ce';
		// const newParsedData = parseNewFormatPacket(newHexData);
		// console.log('新格式解析结果:', newParsedData);
		//
		console.log("res解析",res)
		this.datas = res
		//实时数据
		if (this.datas.slice(4, 6) == '3d') {
			const parsedData = parsePacket(this.datas);
			this.deviceRunInfo = {
				hr: 0,
				runStatus: 0,
				pressure: parsedData.cuffPressureData,
				heartRateStatus: parsedData.heartRateStatus,
			}
			
		} else if (this.datas.slice(4, 6) == '0c') {
			const parsedData = parseNewFormatPacket(this.datas);
			console.log("parsedData解析",parsedData)
			this.deviceRunInfo = {
				...this.deviceRunInfo,
				runStatus: 1,
				systolic_pressure: parsedData.systolicPressure,
				diastolic_pressure: parsedData.diastolicPressure,
				hr: parsedData.heartRate,
				errorCode: parsedData.errorCode,
			}
		} else if (this.datas.slice(4, 6) == '10') {
			//结束
			this.deviceRunInfo = {
				runStatus: -1,
			}
		}else if (this.datas.slice(4, 6) == '40') {
			console.log("判断是否是电量")
			//电量
			const parsedData = parsePacket(this.datas);
			this.battery=parsedData.battery;
			console.log("电量值："+this.battery)
		}
	}



	// 获取设备信息，包括sn，设备类型等

}

function waveFilter(data) {
	// 这里只简单设置阈值[-3, 3]
	return Math.abs(data) > 3 ? (data / Math.abs(data) * 3) : data
}